package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.EquipRegularCheckWorkOrderItem;
import cc.comac.mom.bean.QualityAttachmentGroup;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.dao.entity.EquipRegularCheckPlanDao;
import cc.comac.mom.dao.entity.EquipRegularCheckWorkOrderDao;
import cc.comac.mom.dao.entity.EquipRegularCheckWorkOrderItemDao;
import cc.comac.mom.entity.EquipRegularCheckWorkOrderEntity;
import cc.comac.mom.entity.EquipRegularCheckWorkOrderItemEntity;
import cc.comac.mom.redis.IdFactory;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Component
@Transactional
public class EquipRegularCheckWorkOrderItemDataHandler extends ServiceImpl<EquipRegularCheckWorkOrderItemDao, EquipRegularCheckWorkOrderItemEntity>{
	
	@Autowired
	private EquipRegularCheckWorkOrderItemDao equipRegularCheckWorkOrderItemDao;
	
	@Autowired
	private EquipRegularCheckPlanDao equipRegularCheckPlanDao;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	
	@Autowired
	private EquipRegularCheckWorkOrderDao equipRegularCheckWorkOrderDao;
	
	@Autowired
	private QualityAttachmentGroupDataHandler qualityAttachmentGroupDataHandler;
	@Autowired
	private IdFactory idFactory;
	//批量新增
	public ResultBean insertBatch(List<EquipRegularCheckWorkOrderItem> list) {
		ResultBean resultBean = new ResultBean(true);
		if(list == null || list.size()<1) {
			throw new RuntimeException("数据为空");
		}
		ArrayList<EquipRegularCheckWorkOrderItemEntity> listEntity = new ArrayList<EquipRegularCheckWorkOrderItemEntity>();
		for(EquipRegularCheckWorkOrderItem item :list) {
			EquipRegularCheckWorkOrderItemEntity innerData = item.getInnerData();
			if(innerData == null) {
				throw new RuntimeException("数据为空");
			}
			innerData.setStatus(MomConstants.EQUIP_Regular_CHECK_ORDER_ITEM_STATUS_NOEXECUTE);//待执行
//			baseEntityDataUtil.setBaseEntityData(innerData);
			innerData.setId(idFactory.generateId());
			//	entity.setSiteId(idUtil.getSiteId());
			innerData.setCreationTime(TimeUtil.getLocalDateTime());
			innerData.setCreationTimeZone(TimeUtil.getLocalTimeZone());
			innerData.setLastModifiedTime(TimeUtil.getLocalDateTime());
			innerData.setLastModifiedTimeZone(TimeUtil.getLocalTimeZone());
			innerData.setRowStatus(1);
			listEntity.add(innerData);
		}
		boolean saveBatch = this.saveBatch(listEntity);
		if(!saveBatch) {
			throw new RuntimeException("批量保存定检工单子项失败");
		}
		return resultBean;
	}

	//工单子项执行
	public ResultBean planExecute(EquipRegularCheckWorkOrderItem obj) {
		ResultBean resultBean = new ResultBean(true);
		if(obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipRegularCheckWorkOrderItemEntity innerData = obj.getInnerData();
		EquipRegularCheckWorkOrderItemEntity selectById = equipRegularCheckWorkOrderItemDao.selectById(innerData.getId());
		if(selectById == null) {
			throw new RuntimeException("执行信息不存在");
		}
		//获取定检工单信息
		EquipRegularCheckWorkOrderEntity checkWorkOrderEntity = equipRegularCheckWorkOrderDao.selectById(selectById.getRegularCheckOrderId());
		if(checkWorkOrderEntity == null) {
			throw new RuntimeException("无法获取父级定检工单信息");
		}
		if(checkWorkOrderEntity.getStatus() == MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {	
			throw new RuntimeException("请先开始工单执行");
		}
		baseEntityDataUtil.updateBaseEntityData(checkWorkOrderEntity);
		//判断当前状态是否为待执行
		if(selectById.getStatus() == MomConstants.EQUIP_Regular_CHECK_ORDER_ITEM_STATUS_EXECUTED) {
			throw new RuntimeException("已执行状态不可再次执行");
		}
		//判断前一条计划是否已经执行完成
		QueryWrapper<EquipRegularCheckWorkOrderItemEntity> queryWrapper = new QueryWrapper<EquipRegularCheckWorkOrderItemEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("regular_check_order_id",innerData.getRegularCheckOrderId());
		queryWrapper.lt("benchmark_seq", innerData.getBenchmarkSeq());
		queryWrapper.orderByAsc("benchmark_seq");
		Page<EquipRegularCheckWorkOrderItemEntity> page = new Page<>(0, 1, false);
		
		IPage<EquipRegularCheckWorkOrderItemEntity> iPage = equipRegularCheckWorkOrderItemDao.selectPage(page, queryWrapper);
		List<EquipRegularCheckWorkOrderItemEntity> list = iPage.getRecords();
		if (list !=null && list.size() >0) {
			EquipRegularCheckWorkOrderItemEntity equipRegularCheckWorkOrderItemEntity = list.get(0);
			if(equipRegularCheckWorkOrderItemEntity.getStatus() == MomConstants.EQUIP_Regular_CHECK_ORDER_ITEM_STATUS_NOEXECUTE) {
				throw new RuntimeException("请先执行上一条信息");
			}
		}
		innerData.setExecuteData(TimeUtil.getLocalDate());
		innerData.setStatus(MomConstants.EQUIP_Regular_CHECK_ORDER_ITEM_STATUS_EXECUTED);//已执行
		baseEntityDataUtil.updateBaseEntityData(innerData);
		int updateById = equipRegularCheckWorkOrderItemDao.updateById(innerData);
		if(updateById<1) {
			throw new RuntimeException("执行失败");
		}
		//修改计划工单的状态和执行时长
		   //计算父级工单的执行用时
		Duration duration = Duration.between(TimeUtil.fomatDateToLocalDateTime(checkWorkOrderEntity.getFirstExecuteStartDate()),TimeUtil.getLocalDateTime());
		long hours = duration.toHours();
		checkWorkOrderEntity.setActualExecuteTime(new BigDecimal(hours));
		   //判断是否为最后一条
		QueryWrapper<EquipRegularCheckWorkOrderItemEntity> queryWrapper2 = new QueryWrapper<EquipRegularCheckWorkOrderItemEntity>();
		queryWrapper2.eq("row_status", 1);
		queryWrapper2.eq("regular_check_order_id",innerData.getRegularCheckOrderId());
		queryWrapper2.gt("benchmark_seq", innerData.getBenchmarkSeq());
		queryWrapper2.orderByAsc("benchmark_seq");
		Page<EquipRegularCheckWorkOrderItemEntity> page2 = new Page<>(0, 1, false);
		
		IPage<EquipRegularCheckWorkOrderItemEntity> iPage2 = equipRegularCheckWorkOrderItemDao.selectPage(page2, queryWrapper2);
		List<EquipRegularCheckWorkOrderItemEntity> list2 = iPage2.getRecords();
		if(list2 == null || list2.size()<1) {
			//说明为最后一条，要修改父级状态为执行完成
			checkWorkOrderEntity.setStatus(MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTED);//执行完成
		}
		int updateById2 = equipRegularCheckWorkOrderDao.updateById(checkWorkOrderEntity);
		if(updateById2<1) {
			throw new RuntimeException("修改定检计划工单执行用时失败");
		}
		return resultBean;
	}
	
	// 查询
	public ResultDev selectByCondition(EquipRegularCheckWorkOrderItem obj) {
		QueryWrapper<EquipRegularCheckWorkOrderItemEntity> queryWrapper = new QueryWrapper<EquipRegularCheckWorkOrderItemEntity>();
		queryWrapper.eq("row_status", 1);
		if (obj.getPageSize() == 0) {
			obj.setPageSize(10);
		}
		if (obj != null && obj.getInnerData() != null) {
			if (obj.getInnerData().getRegularCheckOrderId() != 0) {
				queryWrapper.like("regular_check_order_id", obj.getInnerData().getRegularCheckOrderId());
			}
		}
		obj.setPageNum((obj.getPageNum() - 1) * obj.getPageSize());
		queryWrapper.orderByAsc("benchmark_seq");
		Page<EquipRegularCheckWorkOrderItemEntity> page = new Page<>(obj.getPageNum(), obj.getPageSize(), true);
		IPage<EquipRegularCheckWorkOrderItemEntity> iPage = equipRegularCheckWorkOrderItemDao.selectPage(page, queryWrapper);
		List<EquipRegularCheckWorkOrderItemEntity> records = iPage.getRecords();
		if (records != null && records.size() > 0) {
			ArrayList<EquipRegularCheckWorkOrderItem> listEquipRegularCheckWorkOrderItem= new ArrayList<EquipRegularCheckWorkOrderItem>();
			for (EquipRegularCheckWorkOrderItemEntity item : records) {
				EquipRegularCheckWorkOrderItem equipRegularCheckWorkOrderItem = new EquipRegularCheckWorkOrderItem();
				equipRegularCheckWorkOrderItem.setInnerData(item);
				if (item.getAttachmentGroupId() != 0) {
					List<QualityAttachmentGroup> byAttachmentGroupId = qualityAttachmentGroupDataHandler
							.getByAttachmentGroupId(item.getAttachmentGroupId());
					equipRegularCheckWorkOrderItem.setListAttachmentGroup(byAttachmentGroupId);
				}
				listEquipRegularCheckWorkOrderItem.add(equipRegularCheckWorkOrderItem);
			}
			ResultDev resultDev = new ResultDev();
			resultDev.setEntityList(listEquipRegularCheckWorkOrderItem);
			resultDev.setTotalQuantity((int) iPage.getTotal());
			resultDev.setPageCount((int) iPage.getPages());
			return resultDev;

		}
		return null;

	}
}
